package com.lsk.util;

import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.lsk.qiniu.QiniuController;
import jdk.nashorn.internal.runtime.PropertyAccess;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class WxqrcodeUntil {
    /**
     * 获取小程序的accessToken
     * @param
     * @return
     * @throws Exception
     */
    public  static String getAccessToken() throws Exception{
        String sql = "SELECT * FROM weixin_public_account_info WHERE id='3'";
        Record wxConfig = Db.findFirst(sql);
        String appid = wxConfig.get("appId");
        String secret = wxConfig.get("appSecret");
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&" +
                    "&appid=" + appid +
                    "&secret=" + secret;
        JSONObject jsonObject = WxqrcodeUntil.doGetJson(url);
        System.out.println(jsonObject);
        String accessToken = jsonObject.getString("access_token");
        return accessToken;
    }

    /**     发送网络请求的
     * 向微信发请求的      是get请求
     * @param url   url
     * @return
     * @throws Exception
     */
    private static JSONObject doGetJson(String url) throws Exception {
        JSONObject jsonObject = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpclient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
            String result = EntityUtils.toString(httpEntity, "UTF-8");
            jsonObject = new JSONObject(result);
        }
        httpGet.releaseConnection();
        return jsonObject;
    }
    /**
     * 发送网络请求的   可以post也可以get请求
     * @param requestUrl            请求的路径
     * @param requestMethod         GET或者  POST     必须大写
     * @param output                参数
     * @return
     * @throws Exception
     */
    private static String httpsRequest (String requestUrl, String requestMethod, String output) throws Exception {

        String imgpath="";

        URL url = new URL(requestUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod(requestMethod);
        if (null != output) {
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(output.getBytes());
            outputStream.close();
        }
        // 从输入流读取返回内容
        InputStream inputStream = connection.getInputStream();//获取返回值
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
        int line;
        byte[] bytes=new byte[1024];
        while ((line = inputStream.read(bytes))!= -1) {
            bos.write(bytes,0,line);
        }
        inputStream.close();

        Syslog.info("返回字符数组长度为："+bytes.length);

        connection.disconnect();
            Syslog.info("生成小程序二维码错误"+connection.getResponseMessage());
            byte[] buffer = null;
            try {
                byte[] b = new byte[1000];
                int n;
                bos.close();
                buffer = bos.toByteArray();
                imgpath=QiNiuConfig.Quickdomain+ QiniuController.picture(buffer,"QRcode"+ UtilUUID.getUUID()+".jpg");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


        Syslog.info("二维码路径为："+imgpath);

        return imgpath;
    }
    /**
     * 生成小程序码
     * @return
     * @throws Exception
     */
    public static String creatQRcode(String accessToken,String memberId,String ticketId) throws Exception {

        System.out.println("accessToken="+accessToken);
//        String scene=JsonUtil.getJsonStr(map);
        //无限次数的二维码
        String scene=memberId+","+ticketId;
        String urld = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="+accessToken;
        //String d=     "{\"scene\":\""+memberId+"\"}";

        Map<String,Object> parameters=new HashMap<>();

        //parameters.put("scene",scene);
        parameters.put("width",430);
        parameters.put("path","pages/list_detail/list_detail?scene="+scene);

        Syslog.info("生成二维码的请求参数为："+urld);
        Syslog.info(JsonUtil.getJsonStr(parameters));

        String result= WxqrcodeUntil.httpsRequest(urld,"POST",JsonUtil.getJsonStr(parameters));;

        Syslog.info("生成小程序返回结果："+result);
        return result;
    }




    public static void main(String[] args) throws Exception {

    }




}
